<script lang="ts" setup>
import { onMounted } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';

import { ExtendMsgTemplateApi } from '#/api/basic/msg/extendMsgTemplate';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';

import { createCrudOptions } from '../data/def-msg-template-crud';

defineOptions({
  name: '导入系统消息模板',
  inheritAttrs: false,
});

const emit = defineEmits<Emits>();

interface Emits {
  (e: 'success'): void;
}

const { createMessage } = useMessage();
const { crudRef, crudBinding, crudExpose, selectedRowKeys } = useFs({
  createCrudOptions,
});

// 页面打开后获取列表数据
onMounted(async () => {
  crudExpose.doRefresh();
});

const [Modal, modalApi] = useVbenModal({
  async onOpened() {
    selectedRowKeys.value = [];
    crudExpose.doRefresh();
  },
  async onConfirm() {
    await handleSubmit();
  },
});

async function handleSubmit() {
  try {
    modalApi.setState({ loading: true, confirmLoading: true });
    const ids = selectedRowKeys.value;
    if (ids && ids.length > 0) {
      await ExtendMsgTemplateApi.importMsgTemplate(ids);

      createMessage.success($t(`common.tips.importSuccess`));
      modalApi.close();
      emit('success');
    } else {
      createMessage.warning('请选择想要导入的模版');
    }
  } finally {
    modalApi.setState({ loading: false, confirmLoading: false });
  }
}

defineExpose(modalApi);
</script>

<template>
  <Modal title="导入系统模版" class="h-[80%] w-[80%]">
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </Modal>
</template>
